package com.qiwx.pigeon.activity.query;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.andview.refreshview.XRefreshView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.Utils.LogUtil;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.Utils.ScreenUtils;
import com.qiwx.pigeon.adapter.query.WXDCagedapter;
import com.qiwx.pigeon.app.AppContext;
import com.qiwx.pigeon.base.BaseActivity;
import com.qiwx.pigeon.base.BaseMVPActivity;
import com.qiwx.pigeon.data.CageStatusConfig;
import com.qiwx.pigeon.data.db.CageModel;
import com.qiwx.pigeon.data.db.WareHouseModel;
import com.qiwx.pigeon.data.params.CageParam;
import com.qiwx.pigeon.data.vo.CageBean;
import com.qiwx.pigeon.data.vo.CageBeanVo;
import com.qiwx.pigeon.data.vo.QueryCageBean;
import com.qiwx.pigeon.data.vo.WareHouseBean;
import com.qiwx.pigeon.data.vo.pageinfo.PageInfo;
import com.qiwx.pigeon.fragment.ProduceFragment;
import com.qiwx.pigeon.fragment.query.QueryFilterData;
import com.qiwx.pigeon.presenter.CagePresenter;
import com.qiwx.pigeon.presenter.WXDPresenter;
import com.qiwx.pigeon.viewinterface.ICageView;
import com.qiwx.pigeon.viewinterface.IWXDView;
import com.qiwx.pigeon.widget.ArrowView;
import com.qiwx.pigeon.widget.itemderection.CustomGridItemDecoration;

import org.angmarch.views.NiceSpinner;
import org.litepal.LitePal;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fj.dropdownmenu.lib.ion.ViewInject;
import fj.dropdownmenu.lib.ion.ViewUtils;
import fj.dropdownmenu.lib.utils.DropdownUtils;
import fj.dropdownmenu.lib.view.DropdownButton;
import fj.dropdownmenu.lib.view.DropdownColumnView;

import static com.qiwx.pigeon.activity.common.SelectDateActivity.REQUEST_CODE_END;
import static com.qiwx.pigeon.activity.common.SelectDateActivity.REQUEST_CODE_START;

/**
 * @description
 * @Author qiwx
 * @Date 2020-04-15 15:11
 * 未下蛋鸽笼
 **/
public class WXDCageActivity extends BaseMVPActivity<IWXDView, WXDPresenter> implements IWXDView {
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_return)
    ArrowView titleReturn;
    @BindView(R.id.spinner_wh)
    NiceSpinner spinnerWh;
    @BindView(R.id.txt_nodata)
    TextView txtNodata;
    @BindView(R.id.lin_nodata)
    LinearLayout linNodata;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.xRefreshView)
    XRefreshView xRefreshView;
    @BindView(R.id.rel_nodata_recycleview)
    RelativeLayout relNodataRecycleview;
    @BindView(R.id.mask)
    View mask;
    @ViewInject(R.id.drop_days_view)
    @BindView(R.id.drop_days_view)
    DropdownColumnView dropDaysView;
    @ViewInject(R.id.drop_days)
    @BindView(R.id.drop_days)
    DropdownButton dropDays;
    @BindView(R.id.drop_status)
    @ViewInject(R.id.drop_status)
    DropdownButton dropStatus;
    @BindView(R.id.drop_status_view)
    @ViewInject(R.id.drop_status_view)
    DropdownColumnView dropStatusView;
    @BindView(R.id.txt_start_date)
    TextView txtStartDate;
    @BindView(R.id.txt_end_date)
    TextView txtEndDate;
    @BindView(R.id.btn_condition)
    Button btnCondition;
    @BindView(R.id.btn_query)
    Button btnQuery;

    int currentWh_id;
    int wh_number;
    //    int days = 0;
    int offset = 0;//偏移量
    int pageSize = 20;//每页显示20条记录
    List<CageBeanVo> data = new ArrayList<>();
    WXDCagedapter adapter;
    //    long today = 0;
//    long unit_day = 1000 * 60 * 60 * 24;
    int status = 0;
    String startDate = "";
    String endDate = "";
    boolean isFresh = true;
    CageParam cageParam;

    @Override
    public int getLayoutId() {
        return R.layout.activity_query_wxd_cage;
    }

    @Override
    public void initAfterOnCreate() {
        cageParam = new CageParam();
        cageParam.setPageSize(pageSize);
        cageParam.setPageNum(1);
        cageParam.setProduce_status(CageStatusConfig.PRODUCE_KW);
        initView();
        initSpinner();
       // initFilter();
        loadData();
    }

    private void initView() {
        titleReturn.changeArrowLeft();
        titleContent.setText("未下蛋鸽笼");
        btnCondition.setVisibility(View.GONE);
        btnQuery.setVisibility(View.GONE);
        dropStatus.setVisibility(View.GONE);
        long start = DateTimeUtils.addDay(new Date(), -30).getTime();
        long end = DateTimeUtils.getCurrentStamp();
        txtStartDate.setText(DateTimeUtils.timeStamp2Date(start));
        txtEndDate.setText(DateTimeUtils.timeStamp2Date(end));
        startDate = DateTimeUtils.addTimeSuffixNew(txtStartDate.getText().toString(), false) + "";
        endDate = DateTimeUtils.addTimeSuffixNew(txtEndDate.getText().toString(), true) + "";

//        String st1 = DateTimeUtils.timeStamp2DateTime(new Date().getTime());
//        today = DateTimeUtils.addTimeSuffix(st1, true);
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.addItemDecoration(new CustomGridItemDecoration(1));
        adapter = new WXDCagedapter(R.layout.adapter_wxd_list_item, data);
        recyclerview.setAdapter(adapter);
//        adapter.setiCageInterface((pos, c_id, medhid) -> {
//            updateListSelected(pos, c_id, medhid);
//        });
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
               CageBeanVo bean= data.get(position);
               if(bean!=null){
                   checkLayEggRecord(bean.getId(),bean.getNumber());
               }

            }
        });

        xRefreshView.setHideFooterWhenComplete(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                isFresh=true;
                loadData();

            }

            @Override
            public void onLoadMore(boolean isSilence) {
                isFresh=false;
                loadData();
            }
        });


    }

    //查看鸽笼下蛋记录表
    public void checkLayEggRecord(int c_id, int c_number) {
        Intent go = new Intent(this, LayEggRecordActivity.class);
        go.putExtra("c_id", c_id);
        go.putExtra("c_number", c_number);
        startActivity(go);

    }

    private void initFilter() {
        dropStatusView.setVisibility(View.GONE);
        DropdownUtils.init(this, mask);
//        ViewUtils.injectFragmentViews(this, view, mask);
        ViewUtils.injectViews(this, mask);
        //天数
//        dropDaysView.setSingleRow(selectObj -> {
//            days = Integer.valueOf(selectObj.getValue());
//            loadData(true);
//
//        }).setSingleRowList(QueryFilterData.getWXDDays(), 0)  //单列数据
//                .setButton(dropDays) //按钮
//                .show();
        //状态
        dropStatusView.setSingleRow(selectObj -> {
            status = Integer.valueOf(selectObj.getValue());
            isFresh=true;
            loadData();

        }).setSingleRowList(QueryFilterData.getCageStatus(), 0)  //单列数据
                .setButton(dropStatus) //按钮
                .show();
    }

    private void initSpinner() {
        spinnerWh.setPadding(ScreenUtils.dip2px(this, 7), 0, 0, 0);
        List<WareHouseBean> list = AppContext.houses;
        List<String> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            data.add(list.get(i).getNumber() + "号仓");
        }
        spinnerWh.attachDataSource(data);
        spinnerWh.setOnSpinnerItemSelectedListener((parent, view, position, id) -> {
            currentWh_id = list.get(position).getId();
            wh_number = list.get(position).getNumber();
            isFresh=true;
            loadData();

        });
        if (list.size() > 0) {
            currentWh_id = list.get(0).getId();
            wh_number = list.get(0).getNumber();
        }

    }

    private void loadData() {
        cageParam.setWh_id(currentWh_id);
        if (isFresh) {
            cageParam.setPageNum(1);
        } else {
            cageParam.setPageNum(cageParam.getPageNum() + 1);
        }
        cageParam.setStatus(status);
        cageParam.setStartDate(startDate);
        cageParam.setEndDate(endDate);
        mPresenter.queryWXDByPage(cageParam);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_START:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("car_Time_MSG"))) {
                    txtStartDate.setText(data.getStringExtra("car_Time_MSG"));
                    startDate = DateTimeUtils.addTimeSuffixNew(txtStartDate.getText().toString(), false) + "";
                    isFresh=true;
                    loadData();

                }
                break;
            case REQUEST_CODE_END:
                if (data != null && !TextUtils.isEmpty(data.getStringExtra("car_Time_MSG"))) {
                    txtEndDate.setText(data.getStringExtra("car_Time_MSG"));
                    endDate = DateTimeUtils.date2TimeStamp(txtEndDate.getText()
                            .toString(), null) + "";
                    endDate = DateTimeUtils.addTimeSuffixNew(txtEndDate.getText().toString(), true) + "";
                    isFresh=true;
                    loadData();
                }
                break;
        }
    }


    @OnClick({R.id.title_return, R.id.txt_nodata, R.id.txt_start_date, R.id.txt_end_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_return:
                finish();
                break;
            case R.id.txt_start_date:
                selectStartValiDate("开始日期");
                break;
            case R.id.txt_end_date:
                selectEndValiDate(txtStartDate.getText().toString());
                break;
            case R.id.txt_nodata:
                break;
        }
    }


    @Override
    public WXDPresenter createPresenter() {
        return new WXDPresenter(new WeakReference(this));
    }

    @Override
    public void onWXDSuccess(PageInfo<CageBeanVo> result) {

        if (isFresh) {
            data.clear();
        }
        if (result == null || result.getList() == null) {
            if (isFresh) {
                xRefreshView.stopRefresh();
            } else {
                xRefreshView.stopLoadMore();
            }
            return;
        }
        List<CageBeanVo> list = result.getList();
        data.addAll(list);

        if (!isFresh && !result.isHasNextPage()) {
            MyToast.showLong("没有更多数据了");
        }
        LogUtil.e("TAG", list.size() + "");
        if (!result.isHasNextPage()) {
            xRefreshView.setPullLoadEnable(false);
        } else {
            xRefreshView.setPullLoadEnable(true);
        }
        if (isFresh) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();

        }
        adapter.notifyDataSetChanged();

    }

    @Override
    public void onFailed(String error) {

    }
}
